package com.wuhunyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.wuhunyu.commonutils.jwt.JwtUtils;
import com.wuhunyu.entities.UcenterMember;
import com.wuhunyu.mapper.WeChatBackMapper;
import com.wuhunyu.service.WeChatBackService;
import com.wuhunyu.servicebase.exception.Assert;
import com.wuhunyu.utils.HttpClientUtils;
import com.wuhunyu.utils.WeChatConstant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * 微信扫码回调服务实现类
 *
 * @author wuhunyu
 * @version 1.0
 * @date 2021-01-24 10:15
 */
@Service("weChatBackService")
public class WeChatBackServiceImpl implements WeChatBackService {

    @Value("${wechat.open.back_url}")
    private String baseUrl;

    @Resource
    private WeChatBackMapper weChatBackMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String back(String code) {
        // 进行授权认证
        //向认证服务器发送请求换取access_token
        String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        String backUrl = String.format(
                accessTokenUrl,
                WeChatConstant.APP_ID,
                WeChatConstant.APP_SECRET,
                code
        );
        // 发送get请求获取token
        String jsonStr = null;
        try {
            jsonStr = HttpClientUtils.get(backUrl);
        } catch (Exception e) {
            Assert.isRight(false, "转换json字符串失败");
        }
        // 解析json字符串
        Gson gson = new Gson();
        HashMap map = gson.fromJson(jsonStr, HashMap.class);
        // 获取token和登录用户的openid
        String accessToken = (String) map.get("access_token");
        String openid = (String) map.get("openid");
        // 查询该用户是否已经存在
        QueryWrapper<UcenterMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);
        List<UcenterMember> members = weChatBackMapper.selectList(queryWrapper);
        // 用户没有登录过
        if (members == null || members.size() == 0) {
            // 获取用户详情信息
            String userInfoStr = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(
                    userInfoStr,
                    accessToken,
                    openid
            );
            try {
                jsonStr = HttpClientUtils.get(userInfoUrl);
            } catch (Exception e) {
                Assert.isRight(false, "转换json字符串失败");
            }
            map = gson.fromJson(jsonStr, HashMap.class);
            // 获取用户信息
            int sex = (int) (double) map.get("sex");
            String nickname = (String) map.get("nickname");
            String headImgUrl = (String) map.get("headimgurl");
            // 微信获取信息判空可以省略
            // 构造用户对象
            UcenterMember member = new UcenterMember();
            member.setOpenid(openid);
            member.setSex(sex);
            member.setNickname(nickname);
            member.setAvatar(headImgUrl);
            // 执行插入操作
            Assert.isRight(weChatBackMapper.insert(member) != 1, "微信扫码登录失败");
            // 封装jwt token对象
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            return baseUrl + "?token=" + jwtToken;
        }
        // 用户曾经登录过
        // 封装jwt token对象
        String jwtToken = JwtUtils.getJwtToken(members.get(0).getId(), members.get(0).getNickname());
        return baseUrl + "?token=" + jwtToken;
    }
}
